import datetime
import json
import logging
import traceback
from typing import List, Optional, Sequence
from pydantic import BaseModel, Field, validator
from schemas import _validator
logger = logging.getLogger("crud")


class RelatedItem(BaseModel):
    id: int
    status: int = 0
    name: Optional[str] = None

    class Config:
        orm_mode = True


class RelatedItems(BaseModel):
    questionnaire: Sequence[RelatedItem]
    vote: Sequence[RelatedItem]
    lottery: Sequence[RelatedItem]

    class Config:
        orm_mode = True


class ActivityBase(BaseModel):
    accesstoken: Optional[str] = None
    name: str
    start_time: str
    end_time: str
    img_path: List[str] = Field(...)
    desc: str


class ActivityCreate(ActivityBase):
    related_items: RelatedItems = Field(..., alias="related_item")

    create_time: str = datetime.datetime.now().strftime("%Y-%m-%d %X")
    # 转json
    container_json_encode = validator(
        "img_path", "related_items", allow_reuse=True)(
        _validator.container_json_encode)

    class Config:
        schema_extra = {
            "example": {
                  "accesstoken": "TOKEN3590",
                  "name": "活动名称一",
                  "img_path": [
                    "http://slave.homed.me/1.jpg",
                    "http://slave.homed.me/2.jpg"
                  ],
                  "start_time": "2022-03-01 00:00:00",
                  "end_time": "2022-10-01 00:00:00",
                  "desc": "工会组织的活动，评选最美企业",
                  "provider_id": 1,
                  "related_item": {
                    "questionnaire": [
                      {
                        "id": 111
                      }
                    ],
                    "vote": [
                      {
                        "id": 222
                      }
                    ],
                    "lottery": [
                      {
                        "id": 33
                      }
                    ]
                  }
                }
        }


class ActivityAdjust(ActivityCreate):
    id: int


class ActivityDelete(BaseModel):
    accesstoken: Optional[str] = None
    id: List[int]


class Activity(ActivityBase):
    id: int
    create_time: str
    related_item: RelatedItems = Field(..., alias="related_items")

    # 转 dict
    container_json_decode = validator("img_path", "related_item", pre=True, allow_reuse=True)(
        _validator.container_json_decode)
    # datetime 转换
    datetime_str_decode = validator("start_time", "end_time", "create_time", pre=True, allow_reuse=True)(
        _validator.datetime_str_decode)

    class Config:
        orm_mode = True


if __name__ == '__main__':
    from sql_app.database import SessionLocal
    from sql_app.models import TActivity
    from schemas import Activity
    db = SessionLocal()
    res = db.query(TActivity).offset(0).limit(10).all()
    from fastapi.encoders import jsonable_encoder
    print(res[0])
